﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Caching;
using System.Web.UI.WebControls;
using Controllerss;
using Core.Contract.DataContract;
using www.Controllers;
//using www.SService;

namespace www.Admin
{
    public partial class RageComic1 : System.Web.UI.Page
    {
        #region Value
        //private readonly HyServicesClient _hyServicesClient=new HyServicesClient();
        private readonly RageComic_MemeController _rageComicMemeController=new RageComic_MemeController();
        private static int _id;
        private readonly ObjectCache _cache = MemoryCache.Default;
        private static Boolean _insert=false;
        #endregion

        #region Contructor
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if(!IsPostBack)
                    LoadData();
            }
            catch (Exception)
            {
            }
        }
        #endregion

        #region Event
        protected void ddlTypes_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                LoadData();
            }
            catch (Exception)
            {
            }
        }

        protected void lbtinsert_Click(object sender, EventArgs e)
        {
            try
            {
                _insert = true;
                _id = 0;
                pnviews.Visible = false;
                pncontrols.Visible = true;
            }
            catch (Exception)
            {
            }
        }
        protected void lbtdel_Click(object sender, EventArgs e)
        {
            try
            {
                if (grid_Ragecomic.Rows.Count > 0)
                {
                    var lid = new List<long>();
                    for (var i = 0; i < grid_Ragecomic.Rows.Count; i++)
                    {
                        var chk = (CheckBox)grid_Ragecomic.Rows[i].FindControl("chkselect");
                        if (chk.Checked)
                        {
                            var id = ((Label) grid_Ragecomic.Rows[i].FindControl("lblId")).Text;
                            if(!string.IsNullOrEmpty(id) && Convert.ToInt32(id)>0)
                                lid.Add(Convert.ToInt32(id));
                        }
                    }
                    if (lid.Any())
                    {
                        Delete(lid);
                        var lData = (List<RelaxRagcomicMemeDataContract>)_cache["Meme"];
                        if(lData==null)
                            lData=new List<RelaxRagcomicMemeDataContract>();
                        foreach (var Id in lid)
                        {
                            var first = lData.FirstOrDefault(p => p.Id == Id);
                            if (first != null)
                            {
                                Utilities.DeleteFile(Server.MapPath("~/" + first.Image));
                                lData.Remove(first);
                            }
                        }
                        _cache["Meme"] = lData;
                        Message("Có "+lid.Count +" bản ghi xóa thành công.") ;
                    }
                }
            }
            catch (Exception)
            {
            }
        }
        protected void lbtrefresh_Click(object sender, EventArgs e)
        {
            try
            {
                LoadData();
            }
            catch (Exception)
            {
            }
        }

        protected void lbtsave_Click(object sender, EventArgs e)
        {
            try
            {
                SaveData();
            }
            catch (Exception)
            {
            }
        }
        protected void lbtdonew_Click(object sender, EventArgs e)
        {
            try
            {
                Donew();
            }
            catch (Exception)
            {
            }
        }
        protected void lbtback_Click(object sender, EventArgs e)
        {
            try
            {
                Back();
            }
            catch (Exception)
            {
            }
        }

        protected void grid_Ragecomic_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                var id = Convert.ToInt32(e.CommandArgument);
                var lData = (List<RelaxRagcomicMemeDataContract>)_cache["Meme"];
                if (lData == null)
                    lData = new List<RelaxRagcomicMemeDataContract>();
                switch (e.CommandName)
                {
                    case "cmd_edit":
                        var first = lData.FirstOrDefault(p => p.Id == id);
                        if (first == null)
                        {
                            Message("Không có bản ghi nào được sửa.");
                            return;
                        }
                        ddlType.Value = first.Type.ToString();
                        chkactive.Checked = first.Active == 1;
                        _id = id;
                        pncontrols.Visible = true;
                        pnviews.Visible = false;
                        break;
                    case "cmd_delete":
                         var firsts = lData.FirstOrDefault(p => p.Id == id);
                        if (firsts == null)
                        {
                            Message("Không có bản ghi nào được xóa.");
                            return;
                        }
                        Delete(id);
                        Utilities.DeleteFile(Server.MapPath("~/"+firsts.Image));
                        lData.Remove(firsts);
                        LoadData();
                        break;
                    case "cmd_active":
                        var fs = lData.FirstOrDefault(p => p.Id == id);
                        if (fs != null)
                        {
                            fs.Active = fs.Active == 1 ? 0 : 1;
                            _rageComicMemeController.Update(fs);
                        }
                        break;
                }
            }
            catch (Exception)
            {
                
            }
        }

        protected void grid_Ragecomic_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                grid_Ragecomic.PageIndex = e.NewPageIndex;
                LoadData();
            }
            catch (Exception)
            {
               
            }
        }

        #endregion

        #region Business

        private void LoadData()
        {
            var lData = (List<RelaxRagcomicMemeDataContract>) _cache["Meme"];
            if (lData == null)
            {
                lData = _rageComicMemeController.GetRagcomicMemeDataContracts().ToList();
                if (lData.Any())
                {
                    var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(27) };
                    _cache.Set("Meme", lData, policy);
                }
                else
                    lData=new List<RelaxRagcomicMemeDataContract>();
            }
            var lReturn = lData.Where(p => p.Type == Convert.ToInt32(ddlTypes.SelectedValue));
            grid_Ragecomic.DataSource = lReturn;
            grid_Ragecomic.DataBind();
        }

        private void SaveData()
        {
            var lData = (List<RelaxRagcomicMemeDataContract>)_cache["Meme"];
            if(lData==null)
                lData=new List<RelaxRagcomicMemeDataContract>();
            var path = "Images/RagComic/";
            if (!_insert)
            {
                if (_id <= 0)
                {
                    Message("Bạn phải chọn bản ghi cần sửa.");
                    return;
                }
               
                var first =
                       lData.FirstOrDefault(p => p.Id == _id );
                if (first == null)
                    return;
                if (string.IsNullOrEmpty(fufile.PostedFile.FileName))
                    path = first.Image;
                else
                {
                    var ext = new FileInfo(fufile.PostedFile.FileName).Extension;
                    var filename = fufile.PostedFile.FileName.Substring(0,
                        fufile.PostedFile.FileName.IndexOf(ext, StringComparison.Ordinal));
                    var fn = Convert.ToString(Session["StaffId"]) + "_" + DateTime.Now.Year + "_" +
                             DateTime.Now.Month + "_" + DateTime.Now.Day + "_" + DateTime.Now.Hour + "_" +
                             DateTime.Now.Minute + "_" + DateTime.Now.Second + "_" + DateTime.Now.Ticks;
                    filename = fufile.PostedFile.FileName.Replace(filename, fn);

                    path += filename;
                }
                var rage = new RelaxRagcomicMemeDataContract
                {
                    Id = _id,
                    Active = chkactive.Checked?1:0,
                    Image = path,
                    Type = Convert.ToInt32(ddlType.Value)
                };
                if (_rageComicMemeController.Update(rage))
                {
                    first.Image = rage.Image;
                    first.Active = rage.Active;
                    first.Type = rage.Type;

                    _cache["Meme"] = lData;
                    _id = 0;
                    pncontrols.Visible = false;
                    pnviews.Visible = true;
                }
            }
            else
            {
                if (string.IsNullOrEmpty(fufile.PostedFile.FileName))
                {
                    Message("Bạn phải chọn ảnh cần thêm");
                    return;
                }

                var rage = new RelaxRagcomicMemeDataContract
                {
                    Active = chkactive.Checked ? 1 : 0,
                    Image = path,
                    Type = Convert.ToInt32(ddlType.Value)
                };
                var id = _rageComicMemeController.Add(rage);
                if (id > 0)
                {
                    rage.Id = id;
                    lData.Add(rage);
                    _cache["Meme"] = lData;
                    Message("1 bản ghi đã được thêm thành công.");
                }
               
            }
           
        }

        private void Donew()
        {
            chkactive.Checked = false;
        }

        private void Back()
        {
            _insert = false;
            _id = 0;
            pncontrols.Visible = false;
            pnviews.Visible = true;
            LoadData();
        }
        private void Delete(List<long> lid)
        {
            _rageComicMemeController.Delete(lid);
        }

        private void Delete(long id)
        {
            _rageComicMemeController.Delete(new List<long>{id});
        }
        private void Message(string str)
        {
            Response.Write("<script>alert('" + str + "');</script>");
        }
        #endregion
    }
}